package com.lili.divide;

import java.util.Arrays;

/**
 * @Auther: 李 力
 * @Date: 2024/8/20
 * @Description: 数组中位数
 * @version: 1.0
 */
public class ArrayToMiddle {
    public static double findMiddle(int[] nums) {
        Arrays.sort(nums);
        if (nums.length % 2 == 1) {
            //奇数个：中位数就是数组中间索引对应的那个数
            return nums[nums.length / 2];
        } else {
            int a = nums[nums.length / 2];
            int b = nums[nums.length / 2 - 1];
            return (double) (a + b) / 2;
        }
    }

    public static double findMiddle2(int[] nums) {
        if (nums.length % 2 == 1) {
            return QuickSelect.quickSelect(nums, 0, nums.length - 1, nums.length / 2);
        } else {
            int a = QuickSelect.quickSelect(nums, 0, nums.length - 1, nums.length / 2);
            int b = QuickSelect.quickSelect(nums, 0, nums.length - 1, nums.length / 2 - 1);
            return (double) (a + b) / 2;
        }
    }

}
